package com.atguigu.realtime.app.dws;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeSkuOrderBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.function.DimAsyncFunction;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.DimUtil;
import com.atguigu.realtime.util.DruidDSUtil;
import com.atguigu.realtime.util.RedisUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.time.Duration;

/**
 * com.atguigu.realtime.app.dws.Dws_09_DwsTradeSkuOrderWindow
 * 交易域SKU粒度下单各窗口汇总表
 */
public class Dws_09_DwsTradeSkuOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_09_DwsTradeSkuOrderWindow().init(
                4009,
                2,
                "Dws_09_DwsTradeSkuOrderWindow",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 按照 order_detail_id 去重
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        // 2. 把数据封装到pojo中
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStream = parseToPojo(distinctedStream);
        // 3. 按照 sku_id 分组 开窗聚合
        SingleOutputStreamOperator<TradeSkuOrderBean> beanStreamWithoutDim = windowAndAgg(beanStream);

        // 4. 补充维度信息
        addDim(beanStreamWithoutDim);
        // 5. 写出到doris中
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> addDim(
            SingleOutputStreamOperator<TradeSkuOrderBean> beanStreamWithoutDim) {

        // 1. sku  开启异步，使用redis缓存
/*        SingleOutputStreamOperator<TradeSkuOrderBean> skuInfoStream = AsyncDataStream.unorderedWait(
                beanStreamWithoutDim,
                new DimAsyncFunction<TradeSkuOrderBean>() {
                    @Override
                    public String getTable() {
                        return "dim_sku_info";
                    }

                    @Override
                    public String getId(TradeSkuOrderBean input) {
                        return input.getSkuId();
                    }

                    @Override
                    public void addDim(JSONObject dim, TradeSkuOrderBean bean) {
                        bean.setSkuName(dim.getString("SKU_NAME"));
                        bean.setTrademarkId(dim.getString("TM_ID"));
                        bean.setSpuId(dim.getString("SPU_ID"));
                        bean.setCategory3Id(dim.getString("CATEGORY3_ID"));
                    }
                },
                60,
                TimeUnit.SECONDS
        );*/

        // 补充维度信息:条数据, 需要查询6张维度表
        return beanStreamWithoutDim.map(new RichMapFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {

            private Jedis redisClient;
            private DruidDataSource druidDataSource;

            @Override
            public void open(Configuration parameters) throws Exception {
                druidDataSource = DruidDSUtil.getDruidDataSource();  // 连接池
                redisClient = RedisUtil.getRedisClient();
            }

            @Override
            public void close() throws Exception {
                druidDataSource.close();
                redisClient.close(); // 归还redis连接
            }

            @Override
            public TradeSkuOrderBean map(TradeSkuOrderBean bean) throws Exception {
                DruidPooledConnection phoenixConn = druidDataSource.getConnection();
                // 1. 查找dim_sku_info
                // select * from dim_sku_info where id='1';
                // JSONObject : {"列名": 值, ...}
                JSONObject skuInfo = DimUtil.readDim(redisClient, phoenixConn, "dim_sku_info", bean.getSkuId());
                //phoenix里面字段全大写
                bean.setSkuName(skuInfo.getString("SKU_NAME"));
                bean.setTrademarkId(skuInfo.getString("TM_ID"));
                bean.setSpuId(skuInfo.getString("SPU_ID"));
                bean.setCategory3Id(skuInfo.getString("CATEGORY3_ID"));

                //2. tm
                JSONObject baseTrademark = DimUtil.readDim(redisClient, phoenixConn, "dim_base_trademark", bean.getTrademarkId());
                bean.setTrademarkName(baseTrademark.getString("TM_NAME"));

                // 3. spu
                JSONObject spuInfo = DimUtil.readDim(redisClient, phoenixConn, "dim_spu_info", bean.getSpuId());
                bean.setSpuName(spuInfo.getString("SPU_NAME"));

                // 4. c3
                JSONObject c3 = DimUtil.readDim(redisClient, phoenixConn, "dim_base_category3", bean.getCategory3Id());
                bean.setCategory3Name(c3.getString("NAME"));
                bean.setCategory2Id(c3.getString("CATEGORY2_ID"));

                // 5. c2
                JSONObject c2 = DimUtil.readDim(redisClient, phoenixConn, "dim_base_category2", bean.getCategory2Id());
                bean.setCategory2Name(c2.getString("NAME"));
                bean.setCategory1Id(c2.getString("CATEGORY1_ID"));

                // 6. c1
                JSONObject c1 = DimUtil.readDim(redisClient, phoenixConn, "dim_base_category1", bean.getCategory1Id());
                bean.setCategory1Name(c1.getString("NAME"));

                phoenixConn.close();  // 归还给连接池

                return bean;
            }
        });

    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeSkuOrderBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeSkuOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                )
                .keyBy(TradeSkuOrderBean::getSkuId)
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeSkuOrderBean>() {
                            @Override
                            public TradeSkuOrderBean reduce(TradeSkuOrderBean bean1,
                                                            TradeSkuOrderBean bean2) throws Exception {
                                //System.out.println("bean1: " + bean1 + ", bean2: " + bean2);
                                bean1.setOriginalAmount(bean1.getOriginalAmount().add(bean2.getOriginalAmount()));
                                bean1.setActivityAmount(bean1.getActivityAmount().add(bean2.getActivityAmount()));
                                bean1.setCouponAmount(bean1.getCouponAmount().add(bean2.getCouponAmount()));
                                bean1.setOrderAmount(bean1.getOrderAmount().add(bean2.getOrderAmount()));
                                return bean1;
                            }
                        },
                        new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
                            @Override
                            public void process(String skuId,
                                                Context ctx,
                                                Iterable<TradeSkuOrderBean> elements,
                                                Collector<TradeSkuOrderBean> out) throws Exception {
                                TradeSkuOrderBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                                bean.setCurDate(AtguiguUtil.toDate(System.currentTimeMillis()));

                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<TradeSkuOrderBean> parseToPojo(SingleOutputStreamOperator<JSONObject> distinctedStream) {
        return distinctedStream
                .map(new MapFunction<JSONObject, TradeSkuOrderBean>() {
                    @Override
                    public TradeSkuOrderBean map(JSONObject value) throws Exception {
                        // Builder模式来构造对象, 比较方便
                        return TradeSkuOrderBean.builder()
                                .skuId(value.getString("sku_id"))
                                .originalAmount(value.getBigDecimal("split_original_amount"))
                                .orderAmount(value.getBigDecimal("split_total_amount"))
                                .activityAmount(value.getBigDecimal("split_activity_amount") == null ? new BigDecimal(0) : value.getBigDecimal("split_activity_amount"))
                                .couponAmount(value.getBigDecimal("split_coupon_amount") == null ? new BigDecimal(0) : value.getBigDecimal("split_coupon_amount"))
                                .ts(value.getLong("ts") * 1000)
                                .build();
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getString("id"))
                .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {

                    private ValueState<JSONObject> maxTsDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        maxTsDateState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("maxTsDateState", JSONObject.class));
                    }

                    @Override
                    public void processElement(JSONObject value,
                                               Context ctx,
                                               Collector<JSONObject> out) throws Exception {
                        // 定时器触发的时候, 把状态中的数据输出

                        if (maxTsDateState.value() == null) {
                            // 第一条数据来的时候, 把数据存到状态, 注册5s后触发的定时器
                            maxTsDateState.update(value);
                            ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                        } else {
                            //如果不是第一条，则与状态中的数据做对比
                            String last = maxTsDateState.value().getString("row_op_ts");
                            String current = value.getString("row_op_ts");

                            //判断current时间是否大于last,返回true表示大于
                            if (AtguiguUtil.isLarger(current, last)) {
                                maxTsDateState.update(value);
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp,
                                        OnTimerContext ctx,
                                        Collector<JSONObject> out) throws Exception {
                        super.onTimer(timestamp, ctx, out);
                        //当定时器触发的时候，执行这个方法
                        out.collect(maxTsDateState.value());
                    }
                });


    }
}
